#!/bin/bash

# Linux权限维持一键化极简测试脚本
# 使用方法: sudo bash simple_test.sh
# 执行位置: 目标机器上执行

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

# 测试会话ID
TEST_ID=$(date +%Y%m%d_%H%M%S)

echo -e "${BLUE}╔══════════════════════════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║              Linux权限维持一键化极简测试                      ║${NC}"
echo -e "${BLUE}║                    测试ID: $TEST_ID                    ║${NC}"
echo -e "${BLUE}╚══════════════════════════════════════════════════════════════╝${NC}"

# 检查root权限
if [[ $EUID -ne 0 ]]; then
    echo -e "${RED}[错误] 需要root权限，请使用: sudo bash simple_test.sh${NC}"
    exit 1
fi

# 创建测试目录
TEST_DIR="/tmp/persistence_test_$TEST_ID"
mkdir -p "$TEST_DIR"
cd "$TEST_DIR"

echo -e "${GREEN}[信息] 测试目录: $TEST_DIR${NC}"

# 1. SSH密钥后门测试
echo -e "\n${YELLOW}[1/6] 测试SSH密钥后门...${NC}"
ssh-keygen -t rsa -b 2048 -f test_key -N "" -q
mkdir -p ~/.ssh
cp test_key.pub ~/.ssh/authorized_keys_test
echo -e "${GREEN}✓ SSH密钥后门部署成功${NC}"

# 2. Systemd服务后门测试
echo -e "\n${YELLOW}[2/6] 测试Systemd服务后门...${NC}"
cat > /etc/systemd/system/test-maintenance.service << 'EOF'
[Unit]
Description=System Maintenance Service
After=network.target

[Service]
Type=simple
ExecStart=/bin/bash -c 'while true; do echo "$(date): Service running" >> /tmp/test_service.log; sleep 60; done'
Restart=always
User=root

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable test-maintenance.service
systemctl start test-maintenance.service
echo -e "${GREEN}✓ Systemd服务后门部署成功${NC}"

# 3. Crontab后门测试
echo -e "\n${YELLOW}[3/6] 测试Crontab后门...${NC}"
echo "*/5 * * * * echo \"\$(date): Cron job executed\" >> /tmp/test_cron.log" | crontab -
echo -e "${GREEN}✓ Crontab后门部署成功${NC}"

# 4. 环境变量后门测试
echo -e "\n${YELLOW}[4/6] 测试环境变量后门...${NC}"
cat > /etc/profile.d/test-env.sh << 'EOF'
#!/bin/bash
export TEST_PERSISTENCE="active"
if [[ "$TEST_TRIGGER" == "execute" ]]; then
    echo "$(date): Environment trigger activated" >> /tmp/test_env.log
fi
EOF
chmod +x /etc/profile.d/test-env.sh
echo -e "${GREEN}✓ 环境变量后门部署成功${NC}"

# 5. 文件触发后门测试
echo -e "\n${YELLOW}[5/6] 测试文件触发后门...${NC}"
cat > /usr/local/bin/file-monitor << 'EOF'
#!/bin/bash
TRIGGER_FILE="/tmp/trigger_file"
while true; do
    if [[ -f "$TRIGGER_FILE" ]]; then
        echo "$(date): File trigger activated" >> /tmp/test_file_trigger.log
        rm -f "$TRIGGER_FILE"
    fi
    sleep 10
done
EOF
chmod +x /usr/local/bin/file-monitor
nohup /usr/local/bin/file-monitor > /dev/null 2>&1 &
echo -e "${GREEN}✓ 文件触发后门部署成功${NC}"

# 6. Bashrc别名后门测试
echo -e "\n${YELLOW}[6/6] 测试Bashrc别名后门...${NC}"
echo 'alias ll="ls -la; echo \"$(date): Alias executed\" >> /tmp/test_alias.log"' >> ~/.bashrc
echo -e "${GREEN}✓ Bashrc别名后门部署成功${NC}"

# 等待一段时间让服务启动
echo -e "\n${BLUE}[信息] 等待5秒让服务完全启动...${NC}"
sleep 5

# 验证部署结果
echo -e "\n${BLUE}╔══════════════════════════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║                        验证测试结果                          ║${NC}"
echo -e "${BLUE}╚══════════════════════════════════════════════════════════════╝${NC}"

SUCCESS_COUNT=0
TOTAL_COUNT=6

# 验证SSH密钥
if [[ -f ~/.ssh/authorized_keys_test ]]; then
    echo -e "${GREEN}✓ SSH密钥后门验证成功${NC}"
    ((SUCCESS_COUNT++))
else
    echo -e "${RED}✗ SSH密钥后门验证失败${NC}"
fi

# 验证Systemd服务
if systemctl is-active --quiet test-maintenance.service; then
    echo -e "${GREEN}✓ Systemd服务后门验证成功${NC}"
    ((SUCCESS_COUNT++))
else
    echo -e "${RED}✗ Systemd服务后门验证失败${NC}"
fi

# 验证Crontab
if crontab -l | grep -q "test_cron.log"; then
    echo -e "${GREEN}✓ Crontab后门验证成功${NC}"
    ((SUCCESS_COUNT++))
else
    echo -e "${RED}✗ Crontab后门验证失败${NC}"
fi

# 验证环境变量
if [[ -f /etc/profile.d/test-env.sh ]]; then
    echo -e "${GREEN}✓ 环境变量后门验证成功${NC}"
    ((SUCCESS_COUNT++))
else
    echo -e "${RED}✗ 环境变量后门验证失败${NC}"
fi

# 验证文件触发
if pgrep -f "file-monitor" > /dev/null; then
    echo -e "${GREEN}✓ 文件触发后门验证成功${NC}"
    ((SUCCESS_COUNT++))
else
    echo -e "${RED}✗ 文件触发后门验证失败${NC}"
fi

# 验证Bashrc别名
if grep -q "test_alias.log" ~/.bashrc; then
    echo -e "${GREEN}✓ Bashrc别名后门验证成功${NC}"
    ((SUCCESS_COUNT++))
else
    echo -e "${RED}✗ Bashrc别名后门验证失败${NC}"
fi

# 测试触发功能
echo -e "\n${BLUE}[信息] 测试触发功能...${NC}"

# 触发文件监控
touch /tmp/trigger_file
sleep 2

# 触发环境变量
export TEST_TRIGGER="execute"
source /etc/profile.d/test-env.sh

# 显示测试结果
echo -e "\n${BLUE}╔══════════════════════════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║                        测试结果摘要                          ║${NC}"
echo -e "${BLUE}╚══════════════════════════════════════════════════════════════╝${NC}"

echo -e "${GREEN}成功部署: $SUCCESS_COUNT/$TOTAL_COUNT${NC}"
echo -e "${BLUE}成功率: $(( SUCCESS_COUNT * 100 / TOTAL_COUNT ))%${NC}"

if [[ $SUCCESS_COUNT -eq $TOTAL_COUNT ]]; then
    echo -e "${GREEN}🎉 所有权限维持机制部署成功！${NC}"
else
    echo -e "${YELLOW}⚠️  部分权限维持机制部署失败${NC}"
fi

# 显示日志文件
echo -e "\n${BLUE}[信息] 检查生成的日志文件:${NC}"
for log_file in /tmp/test_*.log; do
    if [[ -f "$log_file" ]]; then
        echo -e "${GREEN}✓ $log_file${NC}"
        echo "   内容: $(tail -1 "$log_file" 2>/dev/null || echo "暂无内容")"
    fi
done

# 生成简单报告
REPORT_FILE="/tmp/persistence_test_report_$TEST_ID.txt"
cat > "$REPORT_FILE" << EOF
Linux权限维持一键化测试报告
================================
测试时间: $(date)
测试ID: $TEST_ID
系统信息: $(uname -a)

测试结果:
- 总计测试: $TOTAL_COUNT 项
- 成功部署: $SUCCESS_COUNT 项
- 成功率: $(( SUCCESS_COUNT * 100 / TOTAL_COUNT ))%

部署的权限维持机制:
1. SSH密钥后门: ~/.ssh/authorized_keys_test
2. Systemd服务: test-maintenance.service
3. Crontab任务: 每5分钟执行一次
4. 环境变量: /etc/profile.d/test-env.sh
5. 文件触发: /usr/local/bin/file-monitor
6. Bashrc别名: ~/.bashrc 中的 ll 别名

日志文件位置:
- 服务日志: /tmp/test_service.log
- Cron日志: /tmp/test_cron.log
- 环境变量日志: /tmp/test_env.log
- 文件触发日志: /tmp/test_file_trigger.log
- 别名日志: /tmp/test_alias.log

清理命令:
sudo bash simple_test.sh cleanup
EOF

echo -e "\n${GREEN}📄 详细报告已生成: $REPORT_FILE${NC}"

# 清理选项
if [[ "$1" == "cleanup" ]]; then
    echo -e "\n${YELLOW}[清理] 开始清理测试环境...${NC}"
    
    # 停止并删除服务
    systemctl stop test-maintenance.service 2>/dev/null || true
    systemctl disable test-maintenance.service 2>/dev/null || true
    rm -f /etc/systemd/system/test-maintenance.service
    systemctl daemon-reload
    
    # 清理crontab
    crontab -r 2>/dev/null || true
    
    # 清理环境变量脚本
    rm -f /etc/profile.d/test-env.sh
    
    # 停止文件监控
    pkill -f "file-monitor" 2>/dev/null || true
    rm -f /usr/local/bin/file-monitor
    
    # 清理SSH密钥
    rm -f ~/.ssh/authorized_keys_test
    
    # 清理bashrc别名
    sed -i '/test_alias.log/d' ~/.bashrc 2>/dev/null || true
    
    # 清理日志和临时文件
    rm -f /tmp/test_*.log
    rm -f /tmp/trigger_file
    rm -rf "$TEST_DIR"
    
    echo -e "${GREEN}✓ 清理完成${NC}"
    exit 0
fi

echo -e "\n${BLUE}[提示] 要清理测试环境，请运行: sudo bash simple_test.sh cleanup${NC}"
echo -e "${BLUE}[提示] 测试文件保存在: $TEST_DIR${NC}"

echo -e "\n${GREEN}🚀 测试完成！${NC}"